package tio.study.showcase.server.handler;

import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.json.Json;
import tio.study.showcase.common.ShowcasePacket;
import tio.study.showcase.common.ShowcaseSessionContext;
import tio.study.showcase.common.Type;
import tio.study.showcase.common.intf.AbsShowcaseBsHandler;
import tio.study.showcase.common.packets.P2PReqBody;
import tio.study.showcase.common.packets.P2PRespBody;


/**
 * @author tanyaowu
 * 2017年3月27日 下午9:51:28
 */
@Slf4j
public class P2PReqHandler extends AbsShowcaseBsHandler<P2PReqBody> {

    /**
     * @author: tanyaowu
     */
    public P2PReqHandler() {
    }


    /**
     * @return
     * @author: tanyaowu
     */
    @Override
    public Class<P2PReqBody> bodyClass() {
        return P2PReqBody.class;
    }

    /**
     * @param packet
     * @param bsBody
     * @param channelContext
     * @return
     * @throws Exception
     * @author: tanyaowu
     */
    @Override
    public Object handler(ShowcasePacket packet, P2PReqBody bsBody, ChannelContext channelContext) throws Exception {
        log.info("收到点对点请求消息:{}", Json.toJson(bsBody));

        ShowcaseSessionContext showcaseSessionContext = (ShowcaseSessionContext) channelContext.getAttribute();

        P2PRespBody p2pRespBody = new P2PRespBody();
        p2pRespBody.setFromUserid(showcaseSessionContext.getUserid());
        p2pRespBody.setText(bsBody.getText());

        ShowcasePacket respPacket = new ShowcasePacket();
        respPacket.setType(Type.P2P_RESP);
        respPacket.setBody(Json.toJson(p2pRespBody).getBytes(ShowcasePacket.CHARSET));
        //绑定有用户连接
        Tio.bindUser(channelContext, bsBody.getToUserid());
        Tio.sendToUser(channelContext.getTioConfig(), bsBody.getToUserid(), respPacket);
        return null;
    }

}
